package http

import (
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/dto"
	"gitee.com/captials-team/ubdframe/src/domain/dto/respdata"
	"gitee.com/captials-team/ubdframe/src/domain/vo"
	"gitee.com/captials-team/ubdframe/src/pkg/gin_http"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"gitee.com/captials-team/ubdframe/src/pkg/rsshelp"
	"github.com/gin-gonic/gin"
)

type RssManagerController struct {
	l       v1log.ILog
	fetcher *rsshelp.RssFetcher
	conf    *configstc.RssAppConfig

	gin_http.ResponseController
}

func NewRssManagerController(l v1log.ILog, conf *configstc.RssAppConfig, fetcher *rsshelp.RssFetcher) *RssManagerController {
	ctr := &RssManagerController{
		l:       l,
		fetcher: fetcher,
		conf:    conf,
	}

	return ctr
}

// RssSourceList godoc
// @Summary      RSS源列表
// @Description  rss源列表
// @Tags         rss-manager
// @Produce      json
// @Security     AdminKeyAuth
// @success 200  {object} respdata.ResponseData{data=configstc.RssMetaConfig} "授权成功"
// @success 500 {object} respdata.ResponseData{} "授权失败"
// @Router       /mag/rss/sources [post]
func (ctr *RssManagerController) RssSourceList(ctx *gin.Context) {
	ctr.Response(ctx, respdata.CSuccess.MData(ctr.conf.RssConfig))
}

// RssSourceItems godoc
// @Summary      RSS源文章列表
// @Description  rss源内容列表
// @Tags         rss-manager
// @Produce      json
// @Security     AdminKeyAuth
// @Param        param    body dto.SearchRssContentReq  true  "验证信息"
// @success 200  {object} respdata.ResponseData{data=vo.RssItems} "授权成功"
// @success 500 {object} respdata.ResponseData{} "授权失败"
// @Router       /mag/rss/source/items [post]
func (ctr *RssManagerController) RssSourceItems(ctx *gin.Context) {
	var req dto.SearchRssContentReq
	ctx.ShouldBindJSON(&req)

	var fetcher = ctr.fetcher
	if req.Rss != "" {
		//指定rss
		fetcher = rsshelp.NewRssFetcher(ctr.l)
		fetcher.AddRss("tmp", req.Rss)
	}

	var list []*vo.RssItems
	fetcher.FetchHandler(func(meta *vo.RssMeta, body *vo.RssBody) {
		for _, item := range body.Channel.Items {
			item.Author = meta.Name //修改作者
			list = append(list, item)
		}
	})
	ctr.Response(ctx, respdata.CSuccess.MData(list))
}
